package com.project.market.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.project.market.db.domain.MarketUser;
import com.project.market.service.AdminUserService;
import com.project.market.service.impl.AdminUserServiceImpl;
import com.project.market.util.JacksonUtil;
import com.project.market.util.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.soap.Detail;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/admin/user/*")
public class AdminUserController extends HttpServlet {
    AdminUserService adminUserService = new AdminUserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/user/", "");
        if ("detail".equals(op)) {
            detail(req, resp);
        } else if ("list".equals(op)) {
            list(req, resp);
        }
    }

    private void detail(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        MarketUser list = adminUserService.detail(id);
        if (list == null) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.fail(402, "参数值不对")));
        } else {
            Object ok = ResponseUtil.ok(list);
            String responseBody = JacksonUtil.writeValueAsString(ok);
            resp.getWriter().println(responseBody);
        }
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String page = req.getParameter("page");
        String limit = req.getParameter("limit");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");

        String username = req.getParameter("username");
        String mobile = req.getParameter("mobile");

        List<MarketUser> list = adminUserService.list(page, limit, sort, order, username, mobile);
        Object ok = ResponseUtil.okList(list);
        String responseBody = JacksonUtil.writeValueAsString(ok);
        resp.getWriter().println(responseBody);
    }
}
